<?php

defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 接口权限管理
 * @exception 400 参数错误
 * @exception 502 服务器错误
 * @exception 503 数据库错误
 */
class RightController extends CI_Controller
{
    /**
     * 接口权限
     * @desc 获取接口权限列表
     * @return int id 接口权限id
     * @return string index 接口权限标识
     * @return string name 接口权限名称
     * @throws MyException
     */
    public function right()
    {
        $page = (int)$this->input->get('pageIndex');
        $count = (int) $this->input->get('pageSize',false,10);
        $keyword = (string) $this->input->get('keyword');
        if($keyword)
            $this->db->like('`index`',$keyword)->or_like('name',$keyword);
        $data['total'] = $this->db->select('id, `index`, name')->count_all_results('rights',false);
        $data['data'] = $this->db->order_by('`index`', 'asc')
            ->limit($count,$count*($page-1))
            ->get()->result_array();
        $data['totalPage'] = ceil($data['total'] / $count);
        restful(200, $data);
    }


    /**
     * 接口添加
     */
    public function addRight()
    {

        $data = $this->input->post(['name','index']);
        if(!$data)  throw new MyException('', MyException::INPUT_MISS);
        if(!$this->right->add($data['name'], $data['index']))
            throw new MyException('', MyException::DATABASE);
        restful(201);
    }


    /**
     * 接口修改
     * @param  int|integer $id [ID]
     * @return [type]          [description]
     */
    public function modRight(int $id = 0)
    {
        $data = $this->input->put(['name','index']);
        if(!$data)  throw new MyException('', MyException::INPUT_MISS);
        if(!$this->right->mod($id, $data['name'], $data['index']))
            throw new MyException('', MyException::DATABASE);
        restful();
    }


    /**
     * 删除接口
     * @param int id   [ID]
     */
    public function delRight(int $id =0)
    {
       if($this->right->delete($id))
            restful();
        throw new MyException('', MyException::DATABASE);
    }

}
